import os
import collections
import codeGeneration
from codeGeneration import UE3_VAR_PREFIX, OUTPUT_SINGLE_TABLE_COLUMN, OUTPUT_SINGLE_SPROC_INPUT, ERROR_CANT_OPEN_FILE, OUTPUT_FILE_HEADER_COMMENT, IX_COLUMNNAME, IX_DATATYPE
SHORT_FILENAME = os.path.basename(__file__)
OUTPUT_FILE_HEADER_COMMENT = OUTPUT_FILE_HEADER_COMMENT.replace('{filename}', SHORT_FILENAME)
STATS_SCHEMA = 'dustCharacter'
STATS_DB_TABLE_NAME = 'lifetimeStats'
STATS_DB_PROC_NAME = (STATS_DB_TABLE_NAME[0].upper() + STATS_DB_TABLE_NAME[1:])
OVERWRITE_STATS = ('favoriteWeapon', 'leastFavoriteWeapon', 'favoriteVehicle', 'leastFavoriteVehicle', 'favoriteWeaponInMatch', 'leastFavoriteWeaponInMatch', 'favoriteVehicleInMatch', 'leastFavoriteVehicleInMatch')
IN_MATCH_STATS = ('favoriteWeaponInMatch', 'leastFavoriteWeaponInMatch', 'favoriteVehicleInMatch', 'leastFavoriteVehicleInMatch')

def EmptyDelta():
    return collections.defaultdict(lambda : collections.defaultdict(lambda : 0))



def MergeDeltas(this, other):
    for (charID, statChanges,) in other.items():
        for (statID, statValue,) in statChanges.items():
            if (statID in OVERWRITE_STATS):
                this[charID][statID] = statValue
            else:
                this[charID][statID] += statValue


    return this



def CreateAllStatsFiles(statsList, path):
    statsList.insert(0, ('characterID', 'int'))
    nameData = {'schemaName': STATS_SCHEMA,
     'dbTableName': STATS_DB_TABLE_NAME,
     'lowerTableName': STATS_DB_TABLE_NAME[:-1],
     'keyName': statsList[0][IX_COLUMNNAME],
     'updateProcName': ((STATS_DB_TABLE_NAME[0].upper() + STATS_DB_TABLE_NAME[1:]) + '_Update'),
     'selectProcName': ((STATS_DB_TABLE_NAME[0].upper() + STATS_DB_TABLE_NAME[1:]) + '_Select')}
    sizeData = codeGeneration.GetSQLColumnSizeData(statsList)
    for (index, (statName, statType,),) in enumerate(statsList):
        if (statName != nameData['keyName']):
            if (statType.lower() == 'int'):
                options = 'DEFAULT 0'
            elif (statType.lower() == 'float'):
                options = 'DEFAULT 0.0'
            else:
                raise RuntimeError('Unrecognized column type {0}!'.format(statType))
            statsList[index] = (statName,
             statType,
             options)

    files = []
    filename = codeGeneration.WriteSQLTableFile(nameData, statsList, sizeData, SHORT_FILENAME, lineBreaksAfter=[1])
    if filename:
        files.append(filename)
    filename = codeGeneration.WriteSQLUpdateProcFile(nameData, statsList, sizeData, SHORT_FILENAME, keyColumns=[nameData['keyName']])
    if filename:
        files.append(filename)
    filename = codeGeneration.WriteSQLSelectProcFile(nameData, statsList, sizeData, SHORT_FILENAME, keyColumns=[nameData['keyName']])
    if filename:
        files.append(filename)
    return files



